package com.sync;

/**
 * synchronized方法与锁对象02
 * 学习点01
 * 方法上添加synchronized 为类锁
 * 当访问程序内的类锁时
 * 如果 同时访问另一个有类锁方法时, 则需等待锁
 * 如果 同时访问的方法没有类锁. 则可以异步访问
 *
 * @author bysun
 */
class MyObject01 {
    synchronized public void methodA() {
        try {
            System.out.println("begin method A threadName = " + Thread.currentThread().getName());
            Thread.sleep(2000);
            System.out.println("end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    synchronized public void methodB() {
        try {
            System.out.println("begin method B threadName = " + Thread.currentThread().getName());
            Thread.sleep(2000);
            System.out.println("end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ThreadE extends Thread {
    private MyObject01 myObject;

    public ThreadE(MyObject01 myObject) {
        this.myObject = myObject;
    }

    @Override
    public void run() {
        super.run();
        myObject.methodA();
    }
}

class ThreadF extends Thread {
    private MyObject01 myObject;

    public ThreadF(MyObject01 myObject) {
        this.myObject = myObject;
    }

    @Override
    public void run() {
        super.run();
        myObject.methodB();
    }
}

public class Demo03 {
    public static void main(String[] args) {
        MyObject01 myObject01 = new MyObject01();
        ThreadE threadE = new ThreadE(myObject01);
        threadE.setName("E");
        ThreadF threadF = new ThreadF(myObject01);
        threadF.setName("F");
        threadE.start();
        threadF.start();
    }
}
